<!--
	作者：offline
	时间：2019-04-25
	描述：防伪码查询报表
-->
<template>
	<div class="m-view-barcodeReport m-window">
		<div class="m-condition">
			<el-row :gutter="10" v-if="printShow">
				<el-col :span="2" style="float:right">
					<el-button @click="openSize" v-if="!normalSize">
						<i class="iconfont icon-zhankai"></i>
						<span>展开</span>
					</el-button>
					<el-button @click="retractSize" v-if="normalSize">
						<i class="iconfont icon-shouqi1"></i>
						<span>收缩</span>
					</el-button>
				</el-col>
				<el-col :span="2" :disabled="printDis" style="float:right" v-if="printViewShow">
					<el-button type="primary" @click="printBarcode(2)">打印预览</el-button>
				</el-col>
				<el-col :span="2" :disabled="printDis" style="float:right" v-if="printActionShow">
					<el-button type="primary" @click="printBarcode(1)">打印</el-button>
				</el-col>
				<el-col :span="2" style="float:right">
					<el-button type="primary" @click="searchReport(1)">查询</el-button>
				</el-col>
			</el-row>
			<el-form ref="ruleForm" label-width="70px" :inline-message="true" label-position="left">
				<el-row :gutter="10">
					<el-col :span="6">
						<el-form-item :label="label" class="rightItem">
							<el-select
								value-key="id"
								v-model="searchForm.companyCode"
								:placeholder="`请选择${label}`"
								@change="companyChange"
								ref="content"
								filterable
							>
								<el-option
									v-for="item in comOptions"
									:key="item.id"
									:label="item.companyName"
									:value="item.companyCode"
								></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="4" v-if="searchType=='order'">
						<el-form-item label="采购单号" class="rightItem">
							<el-input v-model="searchForm.purOrdNo" placeholder="请输入采购订单号" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="4" v-if="searchType=='order'">
						<el-form-item label="物料编号" class="rightItem">
							<el-input v-model="searchForm.matCode" placeholder="请输入物料编号" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="6" v-if="searchType=='order'">
						<el-form-item label="订单日期" class="rightItem">
							<el-date-picker
								v-model="searchForm.purOrdDateStart"
								type="date"
								placeholder="订单开始日期"
								value-format="yyyy-MM-dd"
							></el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="4" v-if="searchType=='order'">
						<el-date-picker
							v-model="searchForm.purOrdDateEnd"
							type="date"
							placeholder="订单结束日期"
							value-format="yyyy-MM-dd"
						></el-date-picker>
					</el-col>
					<el-col :span="4" v-if="searchType=='delivery'">
						<el-form-item label="送货日期" class="rightItem">
							<el-date-picker
								v-model="searchForm.deliveryDateStart"
								type="date"
								placeholder="送货开始日期"
								value-format="yyyy-MM-dd"
							></el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="3" v-if="searchType=='delivery'">
						<el-date-picker
							v-model="searchForm.deliveryDateEnd"
							type="date"
							placeholder="送货结束日期"
							value-format="yyyy-MM-dd"
						></el-date-picker>
					</el-col>
					<el-col :span="4" v-if="searchType=='delivery'">
						<el-form-item label="审核日期" class="rightItem">
							<el-date-picker
								v-model="searchForm.auditDateStart"
								type="date"
								placeholder="审核开始日期"
								value-format="yyyy-MM-dd"
							></el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="3" v-if="searchType=='delivery'">
						<el-date-picker
							v-model="searchForm.auditDateEnd"
							type="date"
							placeholder="审核结束日期"
							value-format="yyyy-MM-dd"
						></el-date-picker>
					</el-col>
					<el-col :span="4" v-if="searchType=='barcode'">
						<el-form-item label="生成日期" class="rightItem">
							<el-date-picker
								v-model="searchForm.createDate"
								type="date"
								placeholder="生成日期"
								value-format="yyyy-MM-dd"
							></el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="accountType==4?4:4" v-if="searchType=='barcode'">
						<el-form-item label="生产日期" class="rightItem">
							<el-date-picker
								v-model="searchForm.productDate"
								type="date"
								placeholder="生产日期"
								value-format="yyyy-MM-dd"
							></el-date-picker>
						</el-form-item>
					</el-col>

					<el-col :span="4" v-if="searchType=='delivery'">
						<el-form-item label="送货单号" class="rightItem">
							<el-input v-model="searchForm.deliveryNo" placeholder="请输入送货单号" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="accountType==1?4:5" v-if="searchType=='barcode'">
						<el-form-item label="生产批号" class="rightItem">
							<el-input v-model="searchForm.batchCode" placeholder="请输入生产批号" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="accountType==1?6:5" v-if="searchType=='barcode'">
						<el-form-item label="条码" class="rightItem">
							<el-input v-model="searchForm.barcode" placeholder="请输入条码" clearable></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="10">
					<el-col :span="6" v-if="accountType==1">
						<el-form-item label="供应商" class="rightItem">
							<el-input
								placeholder="请选择供应商"
								v-model="searchForm.supplierName"
								clearable
								@focus="showSupplierDialog"
								readonly
								@mouseenter.native="mouseEnter"
								@mouseleave.native="mounseLeave"
							>
								<el-button slot="append" icon="el-icon-search" @click="showSupplierDialog"></el-button>
								<span slot="suffix" @click="inputClearSon" class="m-cleanInput" v-show="inputClearBut">
									<i class="el-input_icon el-icon-circle-close el-input__clear"></i>
								</span>
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="accountType==4?6:4">
						<el-form-item label="物料名称" class="rightItem">
							<el-input v-model="searchForm.matName" placeholder="请输入物料名称" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col
						:span="accountType==4?4:accountType==1&&searchType=='barcode'?4:3"
						v-if="searchType!='order'"
					>
						<el-form-item label="物料编号" class="rightItem">
							<el-input v-model="searchForm.matCode" placeholder="物料编号" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="accountType==4&&searchType=='delivery'?3:4">
						<el-form-item label="查询模式" class="rightItem">
							<el-select v-model="searchType" placeholder="请选择" @change="typeChange">
								<el-option
									v-for="item in searchOption"
									:key="item.key"
									:label="item.label"
									:value="item.value"
								></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="2" v-if="!printShow" style="float:right">
						<el-button type="primary" @click="searchReport(1)">查询</el-button>
					</el-col>
				</el-row>
			</el-form>
		</div>
		<!--防伪码查询列表-->
		<div class="m-agTable m-bottom m-top5" :class="normalSize ? 'm-top3':'m-top2'">
			<agGridComponents
				ref="reportGrid"
				:isColFit="isColFit"
				:getGridOptions="reportGridOptions"
				:getColumnDefs="reportColumnDefs"
				:getRowSelection="reportRowSelection"
			></agGridComponents>
		</div>
		<!-- 分页组件 -->
		<div class="m-page">
			<el-pagination
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				@prev-click="handlePrevClick"
				@next-click="handleNextClick"
				:current-page="pageInfo.current"
				:page-sizes="[30,50,100,150,200]"
				:page-size="pageInfo.size"
				layout="total, sizes, prev, pager, next, jumper"
				:total="pageInfo.total"
			></el-pagination>
		</div>
		<!-- 供应商弹窗 -->
		<el-dialog
			title="供应商信息"
			:visible.sync="srmSupplierDialogVisible"
			width="50%"
			:before-close="srmSupplierDialogClose"
			v-dialogDrag
			:close-on-click-modal="false"
			:close-on-press-escape="false"
		>
			<srmSupplierInfo ref="srmSupplierInfo" :layout="layout" @setSrmSupplierInfo="setSrmSupplierInfo"></srmSupplierInfo>
		</el-dialog>
		<!-- 已扫码数量弹窗 -->
		<el-dialog
			title="条码信息"
			v-if="barCodeDialogVisible"
			:visible.sync="barCodeDialogVisible"
			width="70%"
			:before-close="barCodeClose"
			v-dialogDrag
			:close-on-click-modal="false"
			:close-on-press-escape="false"
			:inline-message="true"
			class="m-barCode-dialog"
		>
			<el-button type="primary" @click="exportData" v-if="exportBtnShow">导出</el-button>
			<div class="m-barcode-agTableModel">
				<agGridComponents
					ref="barCodeGridComponent"
					:getColumnDefs="codeDialogColumnDefs"
					:isColFit="true"
				></agGridComponents>
			</div>
			<div slot="footer" class="dialog-footer"></div>
		</el-dialog>
	</div>
</template>

<script>
import _Api from "@/api"
import constant from "@/public/constant"
import localeText from "@/i18n/agGridText";
import authInfo from "@/public/authInfo"
import Msg from "@/public/message"
import srmSupplierInfo from "@/components/srmSupplierInfo.vue"
import agGridComponents from "@/components/agGridComponents.js"
import buttonLink from "@/components/buttonLink.js"
import serviceTimes from "@/public/serverTime.js";
import waterfall from "async-es/waterfall";
import fileStream from "@/public/fileStream.js";
import { startPrint } from 'lesso-common/webprint';
import { exportExcel } from 'lesso-common/public/utils';
import apienv from '@/api/env';


const ENV = apienv[constant.appenv]

export default {
	data () {
		return {
			inputClearBut: false,
			label: '',
			// 查询条件  
			searchForm: {
				companyCode: '',
				purOrdDateStart: '',
				purOrdDateEnd: ''
			},
			//查询模式
			searchType: 'order',
			//表格是否自适应窗口宽度
			isColFit: true,
			//是否显示选择供应商弹窗
			srmSupplierDialogVisible: false,
			//是否显示条码信息弹窗
			barCodeDialogVisible: false,
			layout: {},
			comOptions: [],
			// 分页信息
			pageInfo: {
				current: 1,
				size: 30,
				total: 0
			},
			// 查询模式下拉
			searchOption: [
				{ key: 1, value: 'order', label: "按订单" },
				{ key: 2, value: 'delivery', label: "按送货单" },
				{ key: 3, value: 'barcode', label: "按条码" }
			],
			reportGridOptions: {},
			reportColumnDefs: [],
			barCodeColumnDefs: [],
			accountType: "", //账户类型

			//打印按钮添加
			printShow: false,
			isPrint: false,//是否有打印权限
			printActionShow: false,
			printViewShow: false,
			printDis: false,
			// reportRowSelection:"multiple",//控制多选
			reportRowSelection: "single",//控制多选
			normalSize: false,
			printWay: '',
			// 打印状态
			printState: '',
			// 条码集合   
			barcodeArr: [],
			// 导出条码数据参数
			importPramas: {},
			// 是否显示导出按钮
			exportBtnShow: false
		}
	},
	beforeMount () {
		window.addEventListener('setPrint', this.savePrintState)
		this.reportGridOptions = {
			context: {
				componentParent: this
			},
			// rowSelection: "single",
			animateRows: true, //排序动画
			enableFilter: true, //列过滤器
			enableSorting: true, //列排序
			enableCellChangeFlash: true,
			enableRangeSelection: true,
			enableColResize: true,
			localeText: localeText,
		}

		//   按订单查询-表格列信息
		this.reportColumnDefs = [
			{ headerName: "采购订单号", field: "purOrdNo", width: 120 },
			{ headerName: "行项目号", field: "purOrdMxNo", width: 100 },
			{ headerName: "物料编号", field: "matCode", width: 120 },
			{ headerName: "物料描述", field: "matName", width: 150 },
			{
				headerName: "订单日期",
				field: "purOrdDate",
				width: 100,
				cellRenderer: function (params) {
					if (params.value)
						return new Date(params.value).Format("yyyy-MM-dd");
				}
			},
			{ headerName: "供应商", field: "supplierCode", width: 100 },
			{ headerName: "供应商名称", field: "supplierName", width: 150 },
			{ headerName: "公司", field: "companyCode", width: 100 },
			{ headerName: "公司名称", field: "companyName", width: 150 },
			{ headerName: "订单数量", field: "orderAmount", width: 100 },
			{ headerName: "订单单位", field: "unitCode", width: 100 },
			{
				headerName: "已生成条码数",
				field: "genCodeAmount",
				width: 120,
				cellRenderer: buttonLink
			}
		]
		// 按条码查询-表格列信息
		this.barCodeColumnDefs = [
			{
				headerName: "条码",
				field: "",
				checkboxSelection: true,
				// headerCheckboxSelection: true,
				// headerCheckboxSelectionFilteredOnly: true,
				cellRenderer: function (params) {
					if (params.data.barCode) {
						let hideStr = params.data.barCode.substring(4, params.data.barCode.length - 4)
						return params.data.barCode.replace(hideStr, '**********')
					}
				}
			},
			{ headerName: "物料编号", field: "matCode", width: 120 },
			{ headerName: "物料描述", field: "matName", width: 150 },
			{
				headerName: "生成日期",
				field: "createDate",
				width: 120,
				cellRenderer: function (params) {
					if (params.value)
						return new Date(params.value).Format("yyyy-MM-dd");
				}
			},
			{
				headerName: "生产日期",
				field: "productDate",
				width: 120,
				cellRenderer: function (params) {
					if (params.value)
						return new Date(params.value).Format("yyyy-MM-dd");
				}
			},
			{ headerName: "生产批号", field: "batchCode", width: 100 },
			{ headerName: "打印次数", field: "pringCount", width: 100 },
			{ headerName: "关联送货单", field: "deliveryNo", width: 120 },
			{ headerName: "关联订单", field: "purOrdNo", width: 120 },
			{
				headerName: "联塑发货",
				field: "deliveryFlag",
				width: 120,
				cellRenderer: (params) => {
					if (params.value == 1)
						return '<span class="ag-icon">已发货</span>';
					else
						return '<span class="ag-icon">未发货</span>';
				}
			},
			{
				headerName: "扫码保存时间",
				field: "scanCreateDate",
				width: 140,
				cellRenderer: function (params) {
					if (params.value)
						return new Date(params.value).Format("yyyy-MM-dd");
				}
			},
		]
		// 扫码信息弹窗-表格列信息
		this.codeDialogColumnDefs = [
			{
				headerName: "条码",
				field: "",
				width: 120,
				cellRenderer: function (params) {
					if (params.data.barCode) {
						let hideStr = params.data.barCode.substring(4, params.data.barCode.length - 4)
						return params.data.barCode.replace(hideStr, '**********')
					}
				}
			},
			{
				headerName: "生成日期",
				field: "createDate",
				width: 90,
				cellRenderer: function (params) {
					if (params.value)
						return new Date(params.value).Format("yyyy-MM-dd")
				}
			},
			{
				headerName: "生产日期",
				field: "productDate",
				width: 90,
				cellRenderer: function (params) {
					if (params.value)
						return new Date(params.value).Format("yyyy-MM-dd");
				}
			},
			{ headerName: "生产批号", field: "batchCode", width: 90 },
			{ headerName: "打印次数", field: "pringCount", width: 90 },
			{ headerName: "关联送货单", field: "deliveryNo", hide: true, width: 120, tooltipField: 'deliveryNo' },
			{ headerName: "关联订单", field: "purOrdNo", hide: false, width: 100, tooltipField: 'purOrdNo' },
			{
				headerName: "联塑发货",
				field: "deliveryFlag",
				width: 120,
				cellRenderer: (params) => {
					if (params.value == 1)
						return '<span class="ag-icon">已发货</span>';
					else
						return '<span class="ag-icon">未发货</span>';
				}
			},
			{
				headerName: "扫码保存时间",
				field: "createDate",
				width: 120,
				cellRenderer: function (params) {
					if (params.value)
						return new Date(params.value).Format("yyyy-MM-dd");
				}
			},
		]
	},
	mounted () {
		/*
		 * accountType
		 * 1为内部用户
		 * 4为供应商账户
		 */
		this.getBtAuth();
		this.accountType = constant.accountType;
		if (this.accountType == 4) {
			const { supplierCode, supplierName } = constant.supplierData;
			this.searchForm.supplierCode = supplierCode
			this.searchForm.supplierName = supplierName
			this.label = '客户'
		} else {
			this.label = '公司'
		}
		this.initDate(this.searchType)
	},
	components: {
		srmSupplierInfo,
		agGridComponents
	},
	methods: {
		// 点击扫码数量回调
		setClickValue (params, flag) {
			const { deliveryNo, purOrdNo, genCodeAmount, scanAmount, purOrdMxNo, deliveryIMxNo } = params.data
			let obj = {}
			// 根据查询模式不同传参  
			if (deliveryNo) {
				obj = {
					queryType: 'deliveryBarcode',
					deliveryNo,
					deliveryIMxNo
				}
				// 扫码数量大于0,打开弹窗
				if (scanAmount > 0) {
					this.barCodeDialogVisible = true
				} else {
					return false
				}
			} else if (purOrdNo) {
				obj = {
					queryType: 'orderBarcode',
					purOrdNo,
					purOrdMxNo
				}
				// 已生成条码数大于0,打开弹窗
				if (genCodeAmount > 0) {
					this.barCodeDialogVisible = true
				} else {
					return false
				}
			}
			this.importPramas = obj
			this.$nextTick(_ => {
				// 根据订单或送货单号获取条码数据   
				this.$refs.barCodeGridComponent.loading = true
				this.getCodeData(obj).then(data => {
					if (this.$refs.barCodeGridComponent) {
						this.$refs.barCodeGridComponent.gridOptions.api.setRowData(data.rows)
						this.$refs.barCodeGridComponent.loading = false
					}
				})
					.catch(err => {
						Msg.showErrorMsg(err)
					})
				if (this.searchType == 'order') {
					this.$refs.barCodeGridComponent.gridOptions.columnApi.setColumnVisible('deliveryNo', true)
					this.$refs.barCodeGridComponent.gridOptions.columnApi.setColumnVisible('purOrdNo', false)
				} else if (this.searchType == 'delivery') {
					this.$refs.barCodeGridComponent.gridOptions.columnApi.setColumnVisible('deliveryNo', false)
					this.$refs.barCodeGridComponent.gridOptions.columnApi.setColumnVisible('purOrdNo', true)
				}
			})
		},
		// 查询防伪码报表数据
		searchReport (flag) {
			let validat = this.validatQuery(this.searchForm, this.searchType)
			if (flag) this.pageInfo.current = 1
			const { current, size } = this.pageInfo
			const {
				supplierCode,//供应商编码
				companyCode, //公司编码
				purOrdDateStart,//订单开始日期
				purOrdDateEnd,// 订单结束日期
				deliveryDateStart,//送货开始日期
				deliveryDateEnd,//送货结束日期
				auditDateStart, //审核开始日期
				auditDateEnd,//审核结束日期
				productDate,// 生产日期
				createDate,// 生成日期
				purOrdNo,// 订单号
				deliveryNo,// 送货单号
				matName,// 物料名称
				matCode,// 物料编码
				batchCode,// 生产批号
				barcode// 条码
			} = this.searchForm
			if (!validat) return
			let params = {}
			let obj = {
				supplierCode,
				companyCode,
				matName,
				matCode,
				queryType: this.searchType,// order按订单；delivery按送货单；barcode按条码
				currentPage: current,
				pageSize: size
			}
			// 根据查询模式不同传参   
			if (this.searchType == 'order') {
				//   按订单查询
				params = {
					...obj,
					purOrdDateStart,
					purOrdDateEnd,
					purOrdNo
				}
			} else if (this.searchType == 'delivery') {
				// 按送货单查询   
				params = {
					...obj,
					deliveryDateStart,
					deliveryDateEnd,
					auditDateStart,
					auditDateEnd,
					deliveryNo
				}
			} else {
				//   按条码查询
				params = {
					...obj,
					productDate,
					createDate,
					batchCode,
					barCode: barcode
				}
			}
			this.$refs.reportGrid.loading = true
			// 获取报表数据   
			this.getCodeData(params).then(data => {
				if (data.code === 1) {
					let rowData = data.rows
					rowData.forEach(item => {
						if (!item.genCodeAmount) {
							item.genCodeAmount = 0
						}
					})
					this.pageInfo.total = data.total
					this.$refs.reportGrid.gridOptions.api.setRowData(rowData)
					this.$refs.reportGrid.loading = false
				} else {
					this.$refs.reportGrid.loading = false
					Msg.showErrorMsg(err);
					return;
				}
			})
				.catch(err => {
					this.$refs.reportGrid.loading = false
					Msg.showErrorMsg(err)
					return;
				})
		},
		//  验证查询参数
		validatQuery (params, type) {
			const {
				supplierCode,//供应商编码
				companyCode, //公司编码
				purOrdDateStart,//订单开始日期
				purOrdDateEnd,// 订单结束日期
				purOrdNo,// 订单号
				deliveryDateStart,//送货开始日期
				deliveryDateEnd,//送货结束日期
				auditDateStart, //审核开始日期
				auditDateEnd,//审核结束日期
				deliveryNo,// 送货单号
				createDate,// 生成日期
				batchCode,// 生产批号
				barcode,// 条码
				productDate// 生产日期
			} = params
			if (!companyCode) {
				Msg.showPopMsg(`请选择${this.label}`)
				return false
			}
			else if (!supplierCode && this.searchType != 'barcode') {
				Msg.showPopMsg('请选择供应商')
				return false
			}
			if (type == 'order') {
				if (!purOrdNo && !purOrdDateEnd && !purOrdDateStart) {
					Msg.showPopMsg('请填写订单日期、采购单号任意一项进行查询！')
					return false
				} else if (!purOrdDateStart && purOrdDateEnd) {
					Msg.showPopMsg('请选择订单开始日期！')
					return false
				} else if (!purOrdDateEnd && purOrdDateStart) {
					Msg.showPopMsg('请选择订单结束日期！')
					return false
				}
			} else if (type == 'delivery') {
				if (!deliveryNo && !deliveryDateStart && !deliveryDateEnd && !auditDateStart && !auditDateEnd) {
					Msg.showPopMsg('请填写送货日期、审核日期、送货单号任意一项进行查询！')
					return false
				} else if (!deliveryDateStart && deliveryDateEnd) {
					Msg.showPopMsg('请选择送货开始日期！')
					return false
				} else if (!deliveryDateEnd && deliveryDateStart) {
					Msg.showPopMsg('请选择送货结束日期！')
					return false
				} else if (!auditDateStart && auditDateEnd) {
					Msg.showPopMsg('请选择审核开始日期！')
					return false
				} else if (auditDateStart && !auditDateEnd) {
					Msg.showPopMsg('请选择审核结束日期！')
					return false
				}
			} else if (type == 'barcode') {
				if (!productDate && !createDate && !batchCode && !barcode) {
					Msg.showPopMsg('请填写生产日期、生成日期、生产批号、条码号任意一项进行查询！')
					return false
				}
			}
			return true
		},
		// 调接口查询条码数据
		getCodeData (params) {
			return new Promise((resolve, reject) => {
				_Api.getSecurityCodeReport(params).then(res => {
					let data = res.data
					if (data.code == 1) {
						resolve(data)
					} else {
						reject(data.info)
					}
				})
					.catch(err => {
						reject(err.data.message)
					})
			})
		},
		// 选择公司回调
		companyChange (val) {
			if (this.accountType == 1) {
				this.layout.companyCode = val
				this.layout.auth = true
				this.searchForm.supplierCode = ""
				this.searchForm.supplierName = ""
			}
		},
		// 选择查询模式回调
		typeChange (type) {
			this.searchType = type
			this.pageInfo = {
				current: 1,
				size: 30,
				total: 0
			}
			this.$refs.reportGrid.gridOptions.api.setRowData([])
			this.setGirdColumn(type)
		},
		// 输入框清除事件监听
		inputClearSon () {
			this.searchForm.supplierName = ""
			this.searchForm.supplierCode = ""
			this.inputClearBut = false
		},
		// 回显选择的供应商信息
		setSrmSupplierInfo (msg) {
			if (msg.length > 0) {
				const { supplierCode, supplierName } = msg[0]
				this.srmSupplierDialogVisible = false
				this.searchForm.supplierCode = supplierCode
				this.searchForm.supplierName = supplierName
			}
		},
		// 打开供应商弹窗
		showSupplierDialog () {
			let that = this;
			if (!this.layout.companyCode) {
				this.$alert(`提示：请选择${this.label}！`, {
					showClose: false,
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				})
				this.$refs.content.focus()
				return
			} else {
				this.srmSupplierDialogVisible = true
				this.$nextTick(_ => {
					that.$refs.srmSupplierInfo.search()
				})
			}
		},
		// 关闭供应商弹窗回调
		srmSupplierDialogClose (done) {
			this.$refs.srmSupplierInfo.keyWord = ""
			this.$refs.srmSupplierInfo.selSupplierOptions.api.setQuickFilter(
				this.$refs.srmSupplierInfo.keyWord
			)
			done()
		},
		// 关闭条码信息弹窗
		barCodeClose () {
			this.barCodeDialogVisible = false
		},
		// 供应商输入框鼠标移入事件监听
		mouseEnter () {
			const { supplierName } = this.searchForm
			if (supplierName) this.inputClearBut = true
		},
		// 供应商输入框鼠标移出事件监听
		mounseLeave () {
			const { supplierName } = this.searchForm
			if (supplierName) this.inputClearBut = false
		},
		// 每页条数改变回调
		handleSizeChange (size) {
			this.pageInfo.size = size
			this.pageInfo.current = 1
			this.searchReport()
		},
		// 页码改变回调
		handleCurrentChange (current) {
			this.pageInfo.current = current
			this.searchReport()
		},
		// 点击上一页回调
		handlePrevClick (current) {
			this.pageInfo.current = current
		},
		// 点击下一页回调
		handleNextClick (current) {
			this.pageInfo.current = current
		},
		// 根据账户类型获取公司下拉列表
		getCompanyOption () {
			authInfo.getAuthInfo().then(data => {
				this.comOptions = data
				this.searchForm.companyCode = data[0].companyCode
				this.layout.companyCode = data[0].companyCode
				this.layout.auth = true
				if (this.accountType == 4) {
					this.searchReport(1)
				}
			})
				.catch(err => {
					Msg.showErrorMsg(err)
				});
		},
		// 根据查询模式显示不同列
		setGirdColumn (type) {
			let len = this.reportColumnDefs.length
			if (type == 'order') {
				let diffColumn = [
					{ headerName: "采购单号", field: "purOrdNo", width: 120 },
					{ headerName: "行项目号", field: "purOrdMxNo", width: 100 },
					{ headerName: "订单数量", field: "orderAmount", width: 120 },
					{
						headerName: "订单日期",
						field: "purOrdDate",
						width: 100,
						cellRenderer: function (params) {
							if (params.value)
								return new Date(params.value).Format("yyyy-MM-dd");
						}
					},
					{
						headerName: "已生成条码数",
						field: "genCodeAmount",
						width: 120,
						cellRenderer: buttonLink
					}
				]
				this.reportColumnDefs.splice(0, 2, diffColumn[0], diffColumn[1])
				this.reportColumnDefs.splice(9, 1, diffColumn[2])
				this.reportColumnDefs.splice(4, 1, diffColumn[3])
				this.reportColumnDefs.splice(len - 1, 1, diffColumn[4])
				this.$refs.reportGrid.gridOptions.api.setColumnDefs(this.reportColumnDefs)
			} else if (type == 'delivery') {
				let diffColumn = [
					{ headerName: "送货单号", field: "deliveryNo", width: 130 },
					{ headerName: "行号", field: "deliveryIMxNo", width: 70 },
					{ headerName: "送货数量", field: "actualAmount", width: 120 },
					{
						headerName: "送货日期",
						field: "deliveryDate",
						width: 100,
						cellRenderer: function (params) {
							if (params.value)
								return new Date(params.value).Format("yyyy-MM-dd");
						}
					},
					{
						headerName: "扫码数量",
						field: "scanAmount",
						width: 120,
						cellRenderer: buttonLink
					}
				]
				this.reportColumnDefs.splice(0, 2, diffColumn[0], diffColumn[1])
				this.reportColumnDefs.splice(9, 1, diffColumn[2])
				this.reportColumnDefs.splice(4, 1, diffColumn[3])
				this.reportColumnDefs.splice(len - 1, 1, diffColumn[4])
				this.$refs.reportGrid.gridOptions.api.setColumnDefs(this.reportColumnDefs)
			} else {
				this.$refs.reportGrid.gridOptions.api.setColumnDefs(this.barCodeColumnDefs)
			}
		},
		// 初始化查询时间
		initDate (type) {
			// 日期范围默认30天内
			serviceTimes.getServiceTime().then((serviceTime) => {
				let startDate = new Date(serviceTime.getTime() - 3600 * 1000 * 24 * 30).Format('yyyy-MM-dd')
				let endDate = serviceTime.Format("yyyy-MM-dd")
				if (type == 'order') {
					this.searchForm.purOrdDateStart = startDate
					this.searchForm.purOrdDateEnd = endDate
				} else if (type == 'delivery') {
					this.searchForm.deliveryDateStart = startDate
					this.searchForm.deliveryDateEnd = endDate
				} else {
					this.searchForm.productDate = startDate
				}
				this.getCompanyOption()
			}).catch(err => {
				Msg.showErrorMsg(err)
			})
		},
		// web版打印方式
		printOnWeb (printWay) {
			var that = this;
			var printMBMC = '';
			var printId = '';
			var printKey = '';
			var printRows = this.$refs.reportGrid.gridOptions.api.getSelectedRows();
			if (printRows.length <= 0) {
				this.$alert("提示：请选择需要打印的数据", {
					showClose: false,
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				});
				return;
			}
			var tempArr = [];

			let codeObj = {
				supplierCode: printRows[0].supplierCode,
				matCode: printRows[0].matCode,
				type: printRows[0].type,
			}

			_Api.getCodePrintData(codeObj).then(function (response) {
				let data = response.data;
				if (data.code == '1') {
					let codeHeader = data.rows.unitedLabelInfo;
					//配置打印界面数据
					printRows.forEach(item => {
						var obj = {};
						obj.weight = codeHeader.weight;//净重
						obj.shelfLife = codeHeader.shelfLife;//保质期
						obj.model = codeHeader.model;//型号
						obj.execStandard = codeHeader.standard;//执行标准
						obj.produceLocation = codeHeader.productionArea;//产地
						obj.prodName = codeHeader.labMatName;
						obj.matching = codeHeader.matching;
						obj.produceDate = item.productDate;//生产日期
						obj.barcode = constant.barCodePrex + item.barCode;//带地址的条码
						obj.barcode2 = item.barCode;//条码号
						obj.produceNo = item.batchCode;//生产批号
						obj.qualityNo = item.inspectionCode;//质检号
						obj.pigments = item.pigments; //颜色
						obj.shortCode = item.barCode.substring(0, 4) + '-' + item.barCode.substring(item.barCode.length - 4, item.barCode.length);
						tempArr.push(obj);
					});

					if (codeHeader.templateCode == 'paintBarcode') {
						printMBMC = 1;
					} else if (codeHeader.templateCode == 'paintBarcode_1') {
						printMBMC = 2;
					} else {
						printMBMC = 1;
					}
					that.barcodeArr = tempArr
					let paramsTemp = {
						barcodes: tempArr,
						supplierCode: printRows[0].supplierCode,
						matCode: printRows[0].matCode,
						type: printRows[0].type,
					}

					_Api.saveWebCodeInfo(paramsTemp).then(function (response) {
						let data = response.data;
						if (data.code == 1) {
							let tempCodeInfo = data.rows;
							printId = tempCodeInfo.id;
							printKey = tempCodeInfo.key;
							// webapp_urlprotocol_startup()
							if (printWay === 1) {
								// that.updatePrintCount();
								fileStream.getFileInfo(printKey).then((data) => {
									startPrint({
										basicUrl: ENV['srm'], //权限接口地址
										reportUrl: `${ENV['srm']}download2?viewPath=${data.url}&groupName=${data.groupName}`, //打印模板地址
										dataUrl: 'ralOrderBarcode/barcodeInfoToMap', //数据接口地址
										params: {
											'token': '',
											'id': printId,
											'supplierCode': printRows[0].supplierCode,
											'matCode': printRows[0].matCode,
											'type': printMBMC
										}, //参数对象
										printType: 'print',     // 打印方式print直接打印，preview先预览
										storage: that.initStorageEvent
									})
								}).catch((err) => {
									that.$alert(err, {
										showClose: false,
										confirmButton: "确定",
										customClass: "alertFailure"
									});
								})
							} else {
								fileStream.getFileInfo(printKey).then((data) => {
									startPrint({
										basicUrl: ENV['srm'], //权限接口地址
										reportUrl: `${ENV['srm']}download2?viewPath=${data.url}&groupName=${data.groupName}`, //打印模板地址
										dataUrl: 'ralOrderBarcode/barcodeInfoToMap', //数据接口地址
										params: {
											'token': '',
											'id': printId,
											'supplierCode': printRows[0].supplierCode,
											'matCode': printRows[0].matCode,
											'type': printMBMC
										}, //参数对象
										printType: 'preview',     // 打印方式print直接打印，preview先预览
										storage: that.initStorageEvent
									})
								}).catch((err) => {
									that.$alert(err, {
										showClose: false,
										confirmButton: "确定",
										customClass: "alertFailure"
									});
								})
							}
						} else {
							Msg.showErrorMsg('操作失败');
						}
					}).catch((err) => {
						Msg.showErrorMsg(err.data.message);
					})
				}
			})
		},
		// pc版打印条码方法
		printOnPc (printWay) {
			var that = this;
			var printMBMC = '';
			var printRows = this.$refs.reportGrid.gridOptions.api.getSelectedRows();
			if (printRows.length <= 0) {
				this.$alert("提示：请选择需要打印的数据", {
					showClose: false,
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				});
				return;
			}
			var tempArr = [];

			let codeObj = {
				supplierCode: printRows[0].supplierCode,
				matCode: printRows[0].matCode,
				type: printRows[0].type,
			}

			_Api.getCodePrintData(codeObj).then(function (response) {
				let data = response.data;
				if (data.code == '1') {
					let codeHeader = data.rows.unitedLabelInfo;
					//配置打印界面数据
					printRows.forEach(item => {
						var obj = {};
						obj.weight = codeHeader.weight;//净重
						obj.shelfLife = codeHeader.shelfLife;//保质期
						obj.model = codeHeader.model;//型号
						obj.execStandard = codeHeader.standard;//执行标准
						obj.produceLocation = codeHeader.productionArea;//产地
						obj.prodName = codeHeader.labMatName;
						obj.matching = codeHeader.matching;
						obj.produceDate = item.productDate;//生产日期
						obj.barcode = constant.barCodePrex + item.barCode;//带地址的条码
						obj.barcode2 = item.barCode;//条码号
						obj.produceNo = item.batchCode;//生产批号
						obj.qualityNo = item.inspectionCode;//质检号
						obj.pigments = codeHeader.pigments; //颜色
						obj.shortCode = item.barCode.substring(0, 4) + '-' + item.barCode.substring(item.barCode.length - 4, item.barCode.length);
						tempArr.push(obj);
					});
					if (codeHeader.templateCode == 'paintBarcode') {
						printMBMC = 'paintBarcode_pc';
					} else if (codeHeader.templateCode == 'paintBarcode_1') {
						printMBMC = 'paintBarcode_1_pc';
					} else if (codeHeader.templateCode == 'paintBarcode_2') {
						printMBMC = 'paintBarcode_2_pc';
					} else {
						printMBMC = 'paintBarcode_pc';
					}

					if (printWay === 1) {
						if (constant.printType == 'local') {
							ipcRenderer.send("IPCR_M_PRINTLOCAL", {
								// type: "paintBarcode",
								type: printMBMC,
								rows: tempArr,
								// systemType: "srm",
								optype: 'pp',
								isdefaultp: 1//控制是否直接打印,0为选择打印、1为直接打印
							});
							that.updatePrintCount()
						} else {
							fileStream.getFileInfo(printMBMC).then((data) => {
								ipcRenderer.send("IPCR_M_PRINT", {
									type: printMBMC,
									rows: tempArr,
									//   systemType: "srm",
									optype: "pp",
									groupName: data.groupName,
									url: data.url,
									isdefaultp: 1//控制是否直接打印,0为选择打印、1为直接打印
								});
								that.updatePrintCount()
							}).catch((err) => {
								that.$alert(err, {
									showClose: false,
									confirmButton: "确定",
									customClass: "alertFailure"
								});
							})
						}
					} else {
						if (constant.printType == 'local') {
							ipcRenderer.send("IPCR_M_PRINTLOCAL", {
								// type: "paintBarcode",
								type: printMBMC,
								rows: tempArr,
								// systemType: "srm",
								optype: 'pr',
								isdefaultp: 1//控制是否直接打印
							})
						} else {
							fileStream.getFileInfo(printMBMC).then((data) => {
								ipcRenderer.send("IPCR_M_PRINT", {
									type: printMBMC,
									rows: tempArr,
									groupName: data.groupName,
									optype: "pr",
									isdefaultp: 1,//控制是否直接打印
									url: data.url
								});
							}).catch((err) => {
								that.$alert(err, {
									showClose: false,
									confirmButton: "确定",
									customClass: "alertFailure"
								});
							})
						}
					}
				}
			})
		},
		// 打印条码
		printBarcode (printWay) {
			if (constant.userAgent == 'web') {
				this.printOnWeb(printWay)
			} else {
				this.printOnPc(printWay)
			}
		},
		//获取按钮权限
		getBtAuth () {
			var that = this;
			this.isPrint = false;
			this.printActionShow = false;
			this.printViewShow = false;
			this.exportBtnShow = false;
			var obj = {
				type: 1,
				resultType: "0",
				code: 'counterfeitionCodeReport',
				authClientCode: constant.authCode.code,
				authTenantCode: constant.authCode.tcode
			};
			_Api.getUserAuthMenu(obj).then(function (response) {
				var data = response.data;
				if (data.code == "1") {
					if (data.total > 0) {
						for (let i in data.rows) {
							if (data.rows[i].code == "print") {
								that.isPrint = true;
								that.printActionShow = true;
							} else if (data.rows[i].code == "preview") {
								that.isPrint = true;
								that.printViewShow = true;
							} else if (data.rows[i].code == "fwmcx_export") {
								that.exportBtnShow = true
							}
						}
					} else {
						that.isPrint = false;
						that.printActionShow = false;
						that.printViewShow = false;
					}
				}
			}).catch((err) => {
				Msg.showErrorMsg(err.data.message);
			})
		},

		openSize () {
			this.normalSize = true;
		},

		retractSize () {
			this.normalSize = false;
		},

		updatePrintCount () {
			var that = this;
			waterfall([
				function sendIpcRenderer (callback) {
					if (constant.userAgent == 'pc') {
						ipcRenderer.once('IPCR_M_PRINT_RES', (event, arg) => {
							callback(null, arg.printData.rows);
						});
					} else {
						callback(null, that.barcodeArr)
					}
				},
				function updatePrintTime (data, callback) {
					var obj = {};
					var temp = [];
					data.forEach(item => {
						temp.push(item.barcode2);
					});
					obj.barcodes = temp;
					that.printDis = false;
					_Api.updatePrintTime(obj).then(function (response) {
						var data = response.data;
						if (data.code != "1") {
							that.$alert('操作失败！：更新打印次数操作失败！', {
								showClose: false,
								confirmButton: "确定",
								customClass: "alertFailure"
							});
						} else {
							that.searchReport();
						}
					})
				}
			])
		},
		// 保存打印状态到本地存储
		savePrintState () {
			this.printState = sessionStorage.getItem('printType');
		},
		// 注册监听本地存储监听事件
		initStorageEvent (key, newVal) {
			if (key === 'printType') {
				// 创建一个StorageEvent事件
				var newStorageEvent = document.createEvent('StorageEvent');
				const storage = {
					setItem: function (k, val) {
						sessionStorage.setItem(k, val);

						// 初始化创建的事件
						newStorageEvent.initStorageEvent('setPrint', false, false, k, null, val, null, null);

						// 派发对象
						window.dispatchEvent(newStorageEvent)
					}
				}
				return storage.setItem(key, newVal);
			}
		},
		// 导出列表数据
		exportData () {
			let excelData = []
			this.$refs.barCodeGridComponent.loading = true
			this.getCodeData(this.importPramas).then(data => {
				this.$refs.barCodeGridComponent.loading = false
				data.rows.forEach(row => {
					if (this.searchType == 'order') {
						excelData.push({
							'条码': row.barCode,
							'生产日期': row.productDate,
							'生成日期': row.createDate,
							'生产批号': row.batchCode,
							'打印次数': row.pringCount,
							'关联送货单': row.purOrdNo,
							'扫码保存时间': new Date(row.scanCreateDate).Format('yyyy-MM-dd')
						})
					} else {
						excelData.push({
							'条码': row.barCode,
							'生产日期': row.productDate,
							'生成日期': row.createDate,
							'生产批号': row.batchCode,
							'打印次数': row.pringCount,
							'关联送货单': row.deliveryNo,
							'扫码保存时间': new Date(row.scanCreateDate).Format('yyyy-MM-dd')
						})
					}
				})
				let params = {
					data: excelData,
					fileName: '已生成条码明细表.xlsx'
				}
				exportExcel(params)
			})
				.catch(err => {
					this.$refs.barCodeGridComponent.loading = false
					Msg.showErrorMsg(err)
				})
		}
	},

	watch: {
		searchType () {
			if (this.searchType == 'barcode' && this.isPrint == true) {
				this.normalSize = true;
				this.printShow = true;
			} else if (this.searchType == 'order' || this.searchType == 'delivery') {
				this.normalSize = false;
				this.printShow = false;
			}
		},
		printState: {
			handler (newName, oldName) {
				if (newName == 'print') {
					console.log('更新打印次数', newName)
					this.updatePrintCount()
					this.initStorageEvent('printType', '')
				}
			},
			immediate: true
		}
	}
};
</script>

<style>
</style>